import { authenticateToken } from "../../../lib/auth.js";
import { getConnection } from "../../../lib/db.js";
import { validateLookupItem } from "../../../lib/validation.js";

const handler = async function handler(req, res) {
  try {
    const user = req.user;
    const connection = await getConnection();

    if (req.method === "GET") {
      // 获取字典项列表
      const {
        page = 1,
        pageSize = 10,
        search = "",
        status = "",
        type_id = "",
        type_code = "",
      } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(pageSize);

      let whereClause = "WHERE li.tenant_id = ?";
      let queryParams = [user.tenant_id];

      // 通过type_id或type_code筛选
      if (type_id) {
        whereClause += " AND li.type_id = ?";
        queryParams.push(type_id);
      } else if (type_code) {
        whereClause += " AND lt.code = ?";
        queryParams.push(type_code);
      }

      if (search) {
        whereClause +=
          " AND (li.name LIKE ? OR li.code LIKE ? OR li.value LIKE ? OR li.description LIKE ?)";
        const searchParam = `%${search}%`;
        queryParams.push(searchParam, searchParam, searchParam, searchParam);
      }

      if (status !== "") {
        whereClause += " AND li.status = ?";
        queryParams.push(parseInt(status));
      }

      // 获取总数
      const countQuery = `
        SELECT COUNT(*) as total 
        FROM lookup_items li
        LEFT JOIN lookup_types lt ON li.type_id = lt.id
        ${whereClause}
      `;
      const [countResult] = await connection.execute(countQuery, queryParams);
      const total = countResult[0].total;

      // 获取分页数据
      const dataQuery = `
        SELECT li.id, li.type_id, li.parent_id, li.code, li.name, li.value, 
               li.description, li.extra_data, li.level, li.sort_order, 
               li.is_system, li.status, li.created_at, li.updated_at,
               lt.name as type_name, lt.code as type_code,
               CASE WHEN li.parent_id IS NOT NULL THEN p.name ELSE NULL END as parent_name
        FROM lookup_items li
        LEFT JOIN lookup_types lt ON li.type_id = lt.id
        LEFT JOIN lookup_items p ON li.parent_id = p.id
        ${whereClause}
        ORDER BY li.type_id, li.sort_order ASC, li.created_at DESC
        LIMIT ? OFFSET ?
      `;
      queryParams.push(parseInt(pageSize), offset);
      const [rows] = await connection.execute(dataQuery, queryParams);

      // 解析 extra_data JSON
      const data = rows.map((row) => ({
        ...row,
        extra_data: row.extra_data ? JSON.parse(row.extra_data) : null,
      }));

      res.status(200).json({
        success: true,
        data: {
          items: data,
          pagination: {
            page: parseInt(page),
            pageSize: parseInt(pageSize),
            total,
            totalPages: Math.ceil(total / parseInt(pageSize)),
          },
        },
      });
    } else if (req.method === "POST") {
      // 创建字典项
      if (user.role !== "administrator" && user.role !== "operator") {
        return res.status(403).json({
          success: false,
          message: "权限不足，需要管理员或操作员权限",
        });
      }

      const validation = validateLookupItem(req.body);
      if (!validation.success) {
        return res.status(400).json({
          success: false,
          message: validation.message,
          errors: validation.errors,
        });
      }

      const {
        type_id,
        parent_id,
        code,
        name,
        value,
        description,
        extra_data,
        sort_order = 0,
      } = req.body;

      // 验证字典类型是否存在
      const [typeResult] = await connection.execute(
        "SELECT id, is_system FROM lookup_types WHERE id = ? AND tenant_id = ?",
        [type_id, user.tenant_id]
      );

      if (typeResult.length === 0) {
        return res.status(400).json({
          success: false,
          message: "字典类型不存在",
        });
      }

      // 检查代码是否已存在
      const [existingItem] = await connection.execute(
        "SELECT id FROM lookup_items WHERE tenant_id = ? AND type_id = ? AND code = ?",
        [user.tenant_id, type_id, code]
      );

      if (existingItem.length > 0) {
        return res.status(400).json({
          success: false,
          message: "字典项代码在该类型下已存在",
        });
      }

      // 处理层级关系
      let level = 1;
      if (parent_id) {
        const [parentResult] = await connection.execute(
          "SELECT level FROM lookup_items WHERE id = ? AND tenant_id = ? AND type_id = ?",
          [parent_id, user.tenant_id, type_id]
        );

        if (parentResult.length === 0) {
          return res.status(400).json({
            success: false,
            message: "父级字典项不存在",
          });
        }

        level = parentResult[0].level + 1;
      }

      const insertQuery = `
        INSERT INTO lookup_items 
        (tenant_id, type_id, parent_id, code, name, value, description, extra_data, level, sort_order, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
      `;

      const [result] = await connection.execute(insertQuery, [
        user.tenant_id,
        type_id,
        parent_id || null,
        code,
        name,
        value || "",
        description || "",
        extra_data ? JSON.stringify(extra_data) : null,
        level,
        sort_order,
      ]);

      res.status(201).json({
        success: true,
        message: "字典项创建成功",
        data: {
          id: result.insertId,
          code,
          name,
          value,
          level,
        },
      });
    } else {
      res.status(405).json({
        success: false,
        message: "不支持的请求方法",
      });
    }
  } catch (error) {
    console.error("Lookup items API error:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

export default authenticateToken(handler);
